import { ApiContentMenu, ApiJson, onMessage, sendMessage } from "./message";

const contentMenuId = "openapi viewer menu";

const ContentMenuUrls = new Map();

// 注册右击菜单栏
chrome.contextMenus.create({
  id: contentMenuId,
  visible: false,
  title: "载入 OpenApi Viewer",
});

// 更行右击菜单栏配置
function updateContextMenus() {
  const list = [...new Set(ContentMenuUrls.values())];
  chrome.contextMenus.update(contentMenuId, {
    documentUrlPatterns: list,
    visible: !!list.length,
  });
}

// 右击菜单栏点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === contentMenuId) 
    // 告诉注入的脚本，让其将 json 内容发送过来
    sendMessage(ApiJson, null, tab.id);
});

// 浏览请求完成时
chrome.webRequest.onCompleted.addListener(
  (details) => {
    const { responseHeaders, tabId } = details;
    const contentType = responseHeaders?.find(
      ({ name, value }) =>
        name === "Content-Type" && value === "application/json"
    );
    // 请求的资源为 json
    if (contentType) {
      // 注入脚本
      chrome.scripting.executeScript({
        target: { tabId },
        files: ["./dist/content.js"],
      });
    }
  },
  {
    // 匹配的链接
    urls: ["http://*/*", "https://*/*", "file:///*/*"],
    // 请求链接为标签页地址
    types: ["main_frame"],
  },
  ["responseHeaders"]
);

// 标签页移除时
chrome.tabs.onRemoved.addListener((tabId) => {
  if (ContentMenuUrls.has(tabId)) {
    ContentMenuUrls.delete(tabId);
    updateContextMenus();
  }
});

// 监听注入脚本发送的注册右击菜单事件
onMessage(ApiContentMenu, (_, { url, tab }) => {
  ContentMenuUrls.set(tab.id, url);
  updateContextMenus();
});

// 接收注入脚本发送过来的 json 数据
// data 为数据，sender 为发送者的信息
onMessage(ApiJson, (data, sender) => {
  console.log(data);
  console.log(sender);
});
